<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\api\controller\shop;

use app\api\controller\shop\Admin;
use utils\Weixin\WxPay;
use utils\Weixin\WxUser;
use utils\Tools\Express;
use think\Cache;
use think\Queue;
use think\Db;
use Exception;

/**
 * @title 【订单】
 */
class Order extends Admin {
    /*
      const STATUS_TEXT = {
      10: "待付款",
      20: "待发货",
      30: "待收货",
      40: "已完成",
      50: "退款成功",
      60: "交易关闭",
      }
     * 
     */

    /**
     * @title 当前毫秒
     * @return type
     */
    function _getMillisecond() {
        // list($t1, $t2) = explode(' ', microtime());
        //return (float) sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
        list($_, $val) = explode('.', microtime(true));
        return date('YmdHis') . $val;
    }

    /**
     * @title 查询订单物流轨迹
     * @method post
     * @params exp_company_code sto 申通
     * @params waybill_no 3363693982068 申通快递号
     * 
     */
    public function _track($exp_company_code, $waybill_no) {


        $waybill_no = str_replace(' ', '', $waybill_no);


        // 加入缓存
        // 缓存1小时

        $track_name = 'track' . $exp_company_code . $waybill_no;

        $result_cache = Cache::get($track_name);

        if ($result_cache) {

            $result = unserialize($result_cache);

            // 快递公司名称
            $company = $result['result']['company'];

            // 物流信息
            $lists = $result['result']['list'];
            $lists = array_reverse($lists);

            echo json_encode(['code' => 0, 'msg' => '', 'data' => ['no' => $waybill_no, 'company' => $company, 'lists' => $lists]]);
            exit;
        }

        $key = config('express.key');

        $params = array(
            'key' => $key, //您申请的快递appkey
            'com' => $exp_company_code, //快递公司编码，可以通过$exp->getComs()获取支持的公司列表
            'no' => $waybill_no //快递编号
        );
        $exp = new Express($params['key']); //初始化类

        $result = $exp->query($params['com'], $params['no']); //执行查询

        if ($result['error_code'] == 0) {//查询成功
            Cache::set($track_name, serialize($result), 3600);

            // 快递公司名称
            $company = $result['result']['company'];

            // 物流信息
            $lists = $result['result']['list'];
            $lists = array_reverse($lists);


            echo json_encode(['code' => 0, 'msg' => '', 'data' => ['no' => $waybill_no, 'company' => $company, 'lists' => $lists]]);

            // print_r($list);
        } else {
            echo json_encode(['code' => 1, 'msg' => "获取失败，原因：" . $result['reason']]);
        }
    }

    /**
     * @title 查询订单物流轨迹
     * @method post
     * @params order_id 1 订单号
     * 
     */
    public function order_track() {

        $order_id = input('post.order_id', 0);




        if (empty($order_id)) {
            return ['code' => 1, 'msg' => 'params missing'];
        }



        $one = db('order')->where('id', $order_id)->find();

        $express_code = db('express')->where('id', $one['express_id'])->value('code');


        // print_r($one['express_num']);


        if (empty($one['express_number']) || empty($express_code)) {
            return ['code' => 1, 'msg' => '暂无物流信息'];
        } else {
            $this->_track($express_code, $one['express_number']);
        }
    }

    /**
     * @title 售后列表
     * @method post
     * @params status 1 状态
     * @params page 1 默认第1页
     * @params page_size 10 分页数
     */
    public function service() {


        $status = input('post.status', 0);
        $page = input('post.page', 1);
        $page_size = input('post.page_size', 10);


        $where = [
            'member_id' => ['=', UID],
            'status' => ['>', -1]
        ];


        $lists = model('order_service')
                ->alias('a')
                ->join('order_goods og', 'og.id = a.order_goods_id', 'LEFT')
                ->field('a.*, og.order_id')
                ->where($where)
                ->where('status', '=', $status)
                ->order('id desc')
                ->limit(($page - 1) * $page_size, $page_size)
                ->select();

        foreach ($lists as $key => $value) {
            $lists[$key]['orderItem'] = db('order_goods')->where('id', $value['order_goods_id'])->field('id, title, image, price')->find();
        }


        return ['code' => 0, 'msg' => 'success', 'data' => $lists];
    }

    /**
     * @title 申请售后
     * @params order_goods_id 订单商品ID
     * @params type 类型
     * @params quantity 数量
     * @params message 问题描述
     */
    public function service_create() {

        $order_goods_id = request()->post('order_goods_id');
        $type = request()->post('type');
        $quantity = request()->post('quantity');
        $message = request()->post('message');

        if (empty($order_goods_id)) {
            return ['code' => 1, 'msg' => '没有找到相应的商品'];
        }

        // 订单未完成的 不能售后
        $order = db('order_goods')
                ->alias('a')
                ->join('order o', 'o.id = a.order_id')
                ->where('a.id', $order_goods_id)
                ->field('o.status,o.id')
                ->find();


        if ($order['status'] != 40)
            return ['code' => 1, 'msg' => '订单是否未完成？'];

        // 禁止重复提交
        $count = db('order_service')->where('member_id', UID)->where('status', '>', -1)->where('order_goods_id', $order_goods_id)->count();
        if ($count)
            return ['code' => 1, 'msg' => '正在处理中'];


        //添加一条售后        
        $insert_id = db('order_service')->insertGetId([
            'member_id' => UID,
            'order_goods_id' => $order_goods_id,
            'type' => $type,
            'quantity' => $quantity,
            'message' => $message,
            'create_time' => time(),
        ]);


        // 订单中添加一条记录信息
        $type_text = $type == 1 ? '退货' : '换货';
        db('order_history')->insert([
            'order_id' => $order['id'],
            'order_status' => 50,
            'remark' => $type_text . ' 数量' . $quantity . ' ' . $message,
            'member_id' => UID,
            'create_time' => time(),
        ]);


        if ($insert_id) {
            return ['code' => 0, 'msg' => 'success', 'data' => $insert_id];
        } else {
            return ['code' => 1, 'msg' => '提交售后失败,请联系管理员'];
        }
    }

    /**
     * @title 撤销申请 
     * @method post
     * @params service_id 
     * 
     */
    public function service_cancel() {

        $service_id = request()->post('service_id');

        // 
        $affect_rows = db('order_service')->where('member_id', UID)->where('id', $service_id)->setField('status', -1);




        if ($affect_rows) {


            // orderid
            $order_id = db('order_service')
                    ->alias('a')
                    ->join('order_goods og', 'og.id = a.order_goods_id')
                    ->join('order o', 'o.id = og.order_id')
                    ->where('a.id', $service_id)
                    ->value('o.id');

            // 订单记录
            db('order_history')->insert([
                'order_id' => $order_id,
                'order_status' => 52,
                'remark' => '售后撤销',
                'member_id' => UID,
                'create_time' => time(),
            ]);

            return ['code' => 0, 'msg' => 'success', 'data' => $affect_rows];
        } else {
            return ['code' => 1, 'msg' => '撤销失败,请联系管理员'];
        }
    }

    /**
     * @title 售后完成
     * @method post
     * @params service_id 
     * 
     */
    public function service_complete() {

        $service_id = request()->post('service_id');

        // 
        $affect_rows = db('order_service')->where('member_id', UID)->where('id', $service_id)->setField('status', 10);



        if ($affect_rows) {

            // orderid
            $order_id = db('order_service')
                    ->alias('a')
                    ->join('order_goods og', 'og.id = a.order_goods_id')
                    ->join('order o', 'o.id = og.order_id')
                    ->where('a.id', $service_id)
                    ->value('o.id');

            // 订单记录
            db('order_history')->insert([
                'order_id' => $order_id,
                'order_status' => 60,
                'remark' => '售后完成',
                'member_id' => UID,
                'create_time' => time(),
            ]);

            return ['code' => 0, 'msg' => 'success', 'data' => $affect_rows];
        } else {
            return ['code' => 1, 'msg' => '操作失败,请联系管理员'];
        }
    }

    /**
     * @title 评价新增
     * @method post
     * @params order_goods_id 订单商品ID
     * @params content 评价
     * @params rank 评分
     */
    public function evaluate_create() {

        $order_goods_id = request()->post('order_goods_id');
        $content = request()->post('content');
        $rank = request()->post('rank');

        if (empty($content) || empty($order_goods_id)) {
            return ['code' => 1, 'msg' => '评价内容不能为空'];
        }

        // 已评价的商品不能再次评价
        $count = db('goods_evaluate')->where('order_goods_id', $order_goods_id)->count();
        if ($count)
            return ['code' => 1, 'msg' => '已经评价过了'];

        // 订单未完成的 也不能评价
        $status = db('order_goods')
                ->alias('a')
                ->join('order o', 'o.id = a.order_id')
                ->where('a.id', $order_goods_id)
                ->value('o.status');

        if ($status != 40)
            return ['code' => 1, 'msg' => '订单是否未完成？'];




        $goods_id = db('order_goods')->where('id', $order_goods_id)->value('goods_id');

        // 添加一条评价
        $insert_id = db('goods_evaluate')->insertGetId([
            'content' => $content,
            'rank' => $rank,
            'member_id' => UID,
            'goods_id' => $goods_id,
            'order_goods_id' => $order_goods_id,
            'create_time' => time(),
        ]);

        // 更新order_data表中的has字段
        db('order_goods')->where('id', $order_goods_id)->setField('has_evaluate', 1);

        if ($insert_id) {
            return ['code' => 0, 'msg' => 'success', 'data' => $insert_id];
        } else {
            return ['code' => 1, 'msg' => '评价失败'];
        }
    }

    /**
     * @title 用户确认订单
     * @method post
     * @params order_id
     * 状态40
     * 把积分加上去
     */
    public function complete() {

        $status = 40; //订单完成


        $order_id = input('post.order_id');

        if ($order_id) {




            Db::startTrans();
            try {




                $affect_rows = db('order')->where('id', $order_id)->where('member_id', UID)->setField('status', $status);

                // 添加历史记录
                $remark_config = config('order_status');
                $remark = input('post.remark', '');
                if (empty($remark)) {
                    if (isset($remark_config[$status])) {
                        $remark = $remark_config[$status];
                    }
                }

                db('order_history')->insert([
                    'order_id' => $order_id,
                    'member_id' => UID,
                    'order_status' => $status,
                    'remark' => $remark,
                    'create_time' => time()
                ]);



                // 积分加上去                
                $order = db('order')->where('id', $order_id)->where('member_id', UID)->find();

                // 循环看商品的积分值                 
                $points = Db::name('goods')
                        ->where('id', 'IN', function($query) use($order_id) {
                            $query->name('order_goods')->where('order_id', $order_id)->field('goods_id');
                        })
                        ->sum('points');

                if ($order['status'] == 40 && empty($order['delete_time']) && $points > 0) {
                    db('member_points')->insert([
                        'member_id' => $order['member_id'],
                        'points' => $points,
                        'create_time' => time(),
                        'type' => 1,
                        'order_number' => $order['order_number'],
                        'remark' => '购买商品',
                    ]);
                }

                // 把会员积分加上去
                db('member')->where('id', $order['member_id'])->setInc('points', (int) $points);



                /**
                 * 根据用户的积分值 来判断 升级VIP会员的级别
                 */
                $points = db('member')->where('id', $order['member_id'])->value('points');

                // 加载用户的分组,根据分组的积分要求 将用户设置到相应的分组中,从大到小设置
                $member_group = db('member_group')->field('id,points')->order('points desc')->select();

                foreach ($member_group as $key => $value) {
                    if ($points >= $value['points']) {
                        db('member')->where('id', UID)->setField('group_id', $value['id']);
                        break;
                    }
                }


                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ['code' => 1, 'msg' => $e->getMessage()];
            }


            return ['code' => 0, 'msg' => 'success', 'data' => 1];
        } else {

            return ['code' => 1, 'msg' => 'params missing'];
        }
    }

    /**
     * @title 积分兑换商品
     * @method post
     * @params address_id
     * @params goods_id
     */
    public function exchange() {


        $address_id = input('post.address_id', 0);
        $goods_id = input('post.goods_id', 0);



        if (!isset($address_id)) {
            return ['code' => 1, 'msg' => '没有选择收货地址'];
        }
        if (!isset($goods_id)) {
            return ['code' => 1, 'msg' => '没有选择积分商品'];
        }



        // 生成一条待发货的订单
        // 通过 事务的方式


        Db::startTrans();
        try {


            $data['order_number'] = $this->_getMillisecond();
            $data['member_id'] = UID;
            $data['total'] = 0;
            $data['status'] = 20;
            $data['remark'] = '积分兑换';

            // 查询当前地址
            $address_item = db('member_address')->where('id', $address_id)->find();

            if (empty($address_item['phone'])) {
                throw new Exception('收货人电话为空');
            }


            $data['shipping_name'] = $address_item['name'];
            $data['shipping_tel'] = $address_item['phone'];
            $data['shipping_province'] = $address_item['province'];
            $data['shipping_city'] = $address_item['city'];
            $data['shipping_county'] = $address_item['county'];
            $data['shipping_address_detail'] = $address_item['detail'];


            //
            $data['ip'] = get_client_ip();
            $data['user_agent'] = request()->header('user-agent');
            $data['create_time'] = time();


            // 添加主订单表
            $insert_id = db('order')->insertGetId($data);


            // 审计
            db('order_history')->insert([
                'order_id' => $insert_id,
                'order_status' => 20,
                'remark' => $data['remark'],
                'member_id' => UID,
                'create_time' => time(),
            ]);


            $value = db('goods')->where('id', $goods_id)->field('id,title,image,quantity,price,pay_points')->find();

            // 商品图片全路径
            $value['image'] = APP_HOST . APP_URL . DIRECTORY_SEPARATOR . res_http($value['image']);

            // 添加订单关联产品
            db('order_goods')->insert([
                'order_id' => $insert_id,
                'goods_id' => $value['id'],
                'goods_data' => json_encode($value),
                'title' => $value['title'],
                'image' => $value['image'],
                'quantity' => 1,
                'pay_points' => $value['pay_points'],
                'price' => $value['price'],
                'total' => 1 * $value['price'],
            ]);



            // 减去用户的积分
            $member_points = db('member')->where('id', UID)->value('points');
            if ($member_points < $value['pay_points']) {
                throw new Exception('您的积分不够');
            }

            if (db('member')->where('id', UID)->setDec('points', $value['pay_points']) === false) {
                throw new Exception('积分扣减失败，请联系管理员');
            }



            // 用户积分审计
            $member_points_id = db('member_points')->insertGetId([
                'member_id' => UID,
                'points' => $value['pay_points'],
                'create_time' => time(),
                'remark' => '积分兑换商品，订单号：' . $data['order_number'],
                'type' => 0
            ]);

            if (!$member_points_id) {
                throw new Exception('积分审计失败，请联系管理员');
            }




            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => 1, 'msg' => $e->getMessage()];
        }






        if (is_numeric($insert_id)) {
            return ['code' => 0, 'msg' => 'success', 'data' => $insert_id];
        } else {
            return ['code' => 1, 'msg' => $error];
        }
    }

    /**
     * @title 下单
     * @method post
     * @params address_id 0
     * @params remark 
     * @params cart_confirm_items  
     * 这里要插入一个队列，用于60分钟内检测用户是否付款，如果没付款，则删除此订单
     * 状态10
     * 要检查库存是否充足
     */
    function create() {


        $post = input('post.');



        if (!isset($post['address_id']) || empty($post['address_id'])) {
            return ['code' => 1, 'msg' => '没有选择收货地址'];
        }
        if (!isset($post['cart_confirm_items']) || empty($post['cart_confirm_items'])) {
            return ['code' => 1, 'msg' => '购物车里没有任何商品'];
        }


        // 先生成一个订单
        // 订单号、UID、总额、状态、留言 、邮寄地址ID
        // IP信息
        $total = 0;
        foreach ($post['cart_confirm_items'] as $key => $value) {
            $total = $total + $value['price'] * $value['quantity'];
        }


        // 根据用户的头衔，计算折扣
        $member_group = Db::name('member_group')
                ->where('id', '=', function($query) {
                    $query->name('member')->where('id', UID)->field('group_id');
                })
                ->find();

                
        $member_group['discount'] = $member_group['discount'] == 0 ? 100 : $member_group['discount'];        

        $total = $total * ($member_group['discount'] / 100);


        if ($total < 0.01) {
            $total = 0.01;
        }


        // 小于49元，要加6块钱的运费
//        if ($total < 49) {
//            $data['shipping_fee'] = 6;
//        } else {
//            $data['shipping_fee'] = 0;
//        }
        // 事务提交订单
        // 启动事务
        Db::startTrans();
        try {

            if (empty(UID)) {
                throw new Exception('订单无法绑定用户');
            }


            $data['order_number'] = $this->_getMillisecond();
            $data['member_id'] = UID;
            $data['total'] = $total;
            $data['status'] = 10;
            $data['remark'] = empty($post['remark']) ? '下单' : $post['remark'];

            // 查询当前地址
            $address_item = db('member_address')->where('id', $post['address_id'])->find();

            if (empty($address_item['phone'])) {
                throw new Exception('收货人电话为空');
            }


            $data['shipping_name'] = $address_item['name'];
            $data['shipping_tel'] = $address_item['phone'];
            $data['shipping_province'] = $address_item['province'];
            $data['shipping_city'] = $address_item['city'];
            $data['shipping_county'] = $address_item['county'];
            $data['shipping_address_detail'] = $address_item['detail'];

            $data['ip'] = get_client_ip();
            $data['user_agent'] = request()->header('user-agent');
            $data['create_time'] = time();





            // 添加主订单表
            $insert_id = db('order')->insertGetId($data);

            if (!is_numeric($insert_id) || empty($insert_id)) {
                throw new Exception('订单生成失败');
            }




            // 添加一条订单历史记录
            db('order_history')->insert([
                'order_id' => $insert_id,
                'order_status' => 10,
                'remark' => $data['remark'],
                'member_id' => UID,
                'create_time' => time(),
            ]);



            // 订单商品表，依次添加进去
            foreach ($post['cart_confirm_items'] as $key => $value) {
                // 检查库存够不够
                $check = db('goods')->where('id', $value['id'])->field('id,subtract,quantity')->find();




                // 下单会减库存
                if ($check['subtract']) {

                    if ($check['quantity'] < $value['quantity']) {
                        throw new Exception('以下商品缺货，请返回修改' . $value['title']);
                    }

                    db('goods')->where('id', $value['id'])->setDec('quantity', $value['quantity']);
                }

                db('order_goods')->insert([
                    'order_id' => $insert_id,
                    'goods_id' => $value['id'],
                    'goods_data' => json_encode($value),
                    'title' => $value['title'],
                    'image' => $value['image'],
                    'quantity' => $value['quantity'],
                    'price' => $value['price'],
                    'total' => $value['quantity'] * $value['price'],
                ]);
            }




            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => 1, 'msg' => $e->getMessage()];
        }



        // 60分钟后检测订单是否被支付
        // Queue::later(3600, 'app\index\job\Order', ['ts' => time(), 'bizId' => uniqid(), 'id' => $insert_id], 'orderStatusCheck');



        if ($insert_id) {
            return ['code' => 0, 'msg' => 'success', 'data' => $insert_id];
        } else {
            return ['code' => 1, 'msg' => '订单生成失败'];
        }
    }

    /**
     * @title 删除订单
     * @method post
     * @params order_id
     * 软删除
     */
    public function delete() {

        $order_id = input('post.order_id');

        if ($order_id) {


            // 删除订单
            // 把存库依次加上去
            Db::startTrans();
            try {


                //  查找订单
                $order = db('order')->where('id', $order_id)->where('member_id', UID)->find();

                if ($order) {

                    // 依次删除订单商品
                    $order_goods = db('order_goods')->where('order_id', $order['id'])->field('id,goods_id,quantity')->select();

                    // 把存库加上去
                    foreach ($order_goods as $key => $value) {

                        $subtract = db('goods')->where('id', $value['goods_id'])->value('subtract');
                        // 是否加库存
                        if ($subtract)
                            db('goods')->where('id', $value['goods_id'])->setInc('quantity', $value['quantity']);

                        // 删除order_goods
                        db('order_goods')->where('id', $value['id'])->delete();
                    }


                    // 订单删除
                    db('order')->where('id', $order_id)->delete();

                    // 订单历史 删除
                    db('order_history')->where('order_id', $order_id)->delete();
                }else {
                    throw new Exception('没有找到相应的订单');
                }


                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ['code' => 1, 'msg' => $e->getMessage()];
            }

            return ['code' => 0, 'msg' => 'success', 'data' => 1];
        } else {

            return ['code' => 1, 'msg' => 'params missing'];
        }
    }

    /**
     * @title 订单列表
     * @method post
     * @params status 0 0全部10待支付20已支付30交易关闭
     * @params page 1 默认第1页
     * @params page_size 10 分页数
     */
    public function lists() {


        $status = input('post.status', 0);

        $page = input('post.page', 1);
        $page_size = input('post.page_size', 10);

        $where = [];

        if ($status > 0)
            $where['status'] = ['=', $status];



        $where['member_id'] = ['=', UID];
        //  $where['delete_time'] = ['null'];


        $lists = db('order')
                ->field('id,order_number,create_time,remark,status,total,shipping_fee')
                ->where($where)
                ->where('delete_time', 'null')
                ->order('id desc')
                ->limit(($page - 1) * $page_size, $page_size)
                ->select();

        // 把商品的信息附带上去
        foreach ($lists as $key => $value) {

            $goods_lists = db('order_goods')->where('order_id', $value['id'])->select();
            foreach ($goods_lists as $key2 => $value2) {

                $goods_data = json_decode($value2['goods_data'], true);

                $goods_lists[$key2]['title'] = $goods_data['title'];
                $goods_lists[$key2]['image'] = $goods_data['image'];
                unset($goods_lists[$key2]['goods_data']);
            }

            $lists[$key]['orderItems'] = $goods_lists;
        }

        return ['code' => 0, 'msg' => 'success', 'data' => $lists];
    }

    /**
     * @title 查询订单
     * @method post
     * @params order_id 1 
     */
    public function read() {


        $order_id = input('post.order_id');

        if (!$order_id) {
            return ['code' => 1, 'msg' => 'params missing'];
        }

        $one = model('order')->where('id', $order_id)->find();

        // 订单关联商品
        $orderItems = db('order_goods')->where('order_id', $order_id)->select();
        foreach ($orderItems as $key => $value) {
            $orderItems[$key]['has_evaluate'] = db('goods_evaluate')->where('order_goods_id', $value['id'])->count();
        }
        $one['orderItems'] = $orderItems;
        // 订单历史记录
        $lists_history = model('order_history')->where('order_id', $order_id)->select();
        $one['orderHistory'] = $lists_history;

        if ($one) {
            return ['code' => 0, 'msg' => 'success', 'data' => $one];
        } else {
            return ['code' => 1, 'msg' => '订单不存在'];
        }
    }

    /**
     * @title 关闭订单
     * @method post
     * @params order_id
     * 状态60
     */
    public function close() {

        $order_id = input('post.order_id');

        if ($order_id) {

            $affect_rows = db('order')->where('id', $order_id)->where('member_id', UID)->setField('status', 60);

            return ['code' => 0, 'msg' => 'success', 'data' => $affect_rows];
        } else {

            return ['code' => 1, 'msg' => 'params missing'];
        }
    }

    /**
     * @title 小程序支付
     * @method post
     * @params order_id 0
     */
    public function wx_app_pay_sign() {

        $order_id = input('post.order_id');

        if (!$order_id) {
            return ['code' => 1, 'msg' => 'params missing'];
        }


        // 查找订单信息，比如金额
        $one = db('order')->field('id,total,shipping_fee,order_number')->where('id', $order_id)->find();
        if (empty($one)) {
            return ['code' => 1, 'msg' => '订单查找失败'];
        }

        // 获取openid
        $openid = db('member')->where('id', UID)->value('openid');
        if (empty($openid)) {
            return ['code' => 1, 'msg' => 'openid empty'];
        }

        //
        $wxpay = new WxPay([
            'appid' => config('wxapp.appid'),
            'mch_id' => config('wxapp.mch_id'),
            'pay_apikey' => config('wxapp.pay_apikey'),
            'api_cert' => './apiclient_cert.pem',
            'api_key' => './apiclient_key.pem'
        ]);


        $data = $wxpay->pay_first($openid, $one['total'] + $one['shipping_fee'], $one['order_number']);


        return ['code' => 0, 'msg' => 'success', 'data' => $data];
    }

    /**
     * @title 获取微信支付签名
     * @method post
     * @params order_id 1 
     */
    public function wx_pay_sign() {


        $order_id = input('post.order_id');

        if (!$order_id) {
            return ['code' => 1, 'msg' => 'params missing'];
        }


        //微信支付       
        $appid = config('weixin.appid');
        $appsecret = config('weixin.appsecret');
        $wxuser = new WxUser($appid, $appsecret);

        $userInfo = $wxuser->getWxUserInfo(APP_HOST . url('api/shop.everyone/wx_login'));



        $wxpay = new WxPay();




        if (isset($userInfo['openid']) && !empty($userInfo['openid'])) {

            $one = db('order')->where('id', $order_id)->find();

            $result = $wxpay->pay_first($userInfo['openid'], $one['total'] + $one['shipping_fee'], $one['order_number']);

            return ['code' => 0, 'msg' => 'success', 'data' => $result];
        } else {

            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        }
    }

}
